var url = "http://127.0.0.1:8083/";


function getCookie(key){
    var cookie = document.cookie;
    var s = cookie.replace("; ","=");
    while (s.indexOf(";") != -1){
        s = s.replace("; ","=");
    }
    var strings = s.replace("; ","=").split("=");
    if (strings.indexOf(key) == -1){
        return null;
    }
    return strings[strings.indexOf(key) + 1].trim();
}

$(function () {
    $.ajax({
        url: url + "cart/getCartList",
        type: "POST",
        data: {userName: getCookie("USER_NAME")},
        success: function (data) {
            if (data["code"] == 200) {
                var datum = data["data"];
                for (let i = 0; i < datum.length; i++) {
                    $(".mycart .card .card-body .table tbody").append(
                        "<tr>\n" +
                        "    <td>\n" +
                        "        <div class=\"center\">\n" +
                        "            <input type=\"hidden\" name=\"productId\" class=\"shopid\" value=\" " + datum[i]["carId"] + " \"/>\n" +
                        "            <img src=\"" + datum[i]["product"]["productPicture"] + "\" alt=\"\">\n" +
                        "        </div>\n" +
                        "    </td>\n" +
                        "    <td>\n" +
                        "        " + datum[i]["product"]["productName"] + "\n" +
                        "    </td>\n" +
                        "    <td>\n" +
                        "        ￥ <span class=\"unit-price\">" + datum[i]["product"]["productPrice"] + "</span>\n" +
                        "    </td>\n" +
                        "    <td>\n" +
                        "        <div class=\"quick-add-to-cart\">\n" +
                        "            <form method=\"post\" class=\"cart\">\n" +
                        "                <div class=\"numbers-row\">\n" +
                        "                    <div><a href=\"javascript:void(0);\" class=\"btn btn-rounded btn-info reduce-amount\" onclick='reduce(this)'>-</a></div>\n" +
                        "                    <input type=\"number\" class=\"count\" value=\"" + parseInt(datum[i]["carCount"]) + "\" onKeypress=\"return (/[\\d.]/.test(String.fromCharCode(event.keyCode)))\" onchange='changeCount(this)'/>\n" +
                        "                    <div><a href=\"javascript:void(0);\" class=\"btn btn-rounded btn-info add-amount\" onclick='add(this)'>+</a></div>\n" +
                        "                </div>\n" +
                        "            </form>\n" +
                        "        </div>\n" +
                        "    </td>\n" +
                        "    <td>\n" +
                        "        ￥<span class=\"sum-amount\">" + (parseFloat(datum[i]["product"]["productPrice"]) * parseInt(datum[i]["carCount"])) + "</span>\n" +
                        "    </td>\n" +
                        "    <td>\n" +
                        "        <a href=\"javascript:void(0);\" class=\"btn\" onclick='toCheck(this)'>\n" +
                        "            <i class=\"fa fa-check\">结算</i>\n" +
                        "        </a>\n" +
                        "        <a href=\"javascript:void(0);\" class=\"btn\"onclick='del(this)'>\n" +
                        "            <i class=\"fa fa-trash\">删除</i>\n" +
                        "        </a>\n" +
                        "    </td>\n" +
                        "</tr>"
                    )
                }
            }else if (data["code"] == 405) {
                window.location.href=url + "user/" + data["data"]+".html";
            }
        }
    });
});

function reduce(obj) {
    var $count = $(obj).parent().next(".count");
    var td = $(obj).parent().parent().parent().parent().parent();
    var count = parseInt($count.val());
    //获取单价
    var unit_price = td.prev().find(".unit-price").text();
    //总价
    var sum_amount = td.next().find(".sum-amount");

    if (parseInt($count.val()) <= 1) {
        count=1;
        $count.val(count);
        return;
    } else {
        $count.val(--count);
    }

    changeAmount(td, unit_price,sum_amount, count);
}

function add(obj) {
    var $count = $(obj).parent().prev(".count");
    var td = $(obj).parent().parent().parent().parent().parent();
    var sum_amount = td.next().find(".sum-amount");
    var unit_price = td.prev().find(".unit-price").text();
    var count = parseInt($count.val());

    $count.val(++count);

    changeAmount(td, unit_price,sum_amount, count);
}

function changeCount(obj) {
    var td = $(obj).parent().parent().parent().parent();
    var count = $(obj).val();
    //获取单价
    var unit_price = td.prev().find(".unit-price").text();
    //总价
    var sum_amount = td.next().find(".sum-amount");
    count = parseInt(count);

    changeAmount(td, unit_price,sum_amount, count);
}

function changeAmount(obj,unit_price,sum_amount,count) {
    var cart = {};
    cart["carCount"] = count;
    var shopid = $(obj).parent().find(".shopid");
    cart["carId"] = parseInt(shopid.val());
    $.ajax({
        url: url + "cart/update",
        type: "POST",
        contentType:"application/json;charset=UTF-8",
        async: false,
        data: JSON.stringify(cart),
        dataType: "json",
        success: function (data) {
            console.log(data['data']);
            if (data["code"] == 200) {
                unit_price = parseFloat(unit_price);
                var sum = unit_price * count;
                sum_amount.text(sum.toFixed(2));
            }
        }
    })
}

function toCheck(obj) {
    var carId = $(obj).parent().parent().find(".center").find(".shopid");
    carId = parseInt(carId.val());

    $.ajax({
        url: url + "order/setOrder",
        type: "POST",
        data: {carId: carId},
        success: function (data) {
            if (data["code"] == 200) {
                window.location.href=url + "user/" + data["data"] + ".html"
            }
        }
    });
}

function del(obj) {
    var carId = $(obj).parent().parent().find(".center").find(".shopid");
    carId = parseInt(carId.val());
    $.ajax({
        url: url + "cart/delete",
        type: "POST",
        data: {carId: carId},
        success:function (data) {
            if(data["code"] == 200){
                $(obj).parent().parent().remove();
            }
        }
    })

}